<?php
// 引入配置文件和SQL函数
require_once 'resource/config.php';
require_once 'resource/sql_commands.php';

// 获取数据库配置
$db_name = getCurrentDatabaseName();

// 创建连接
$conn = getDbConnection();

// 获取所有表
//$sql = "SHOW TABLES";
$sql = "SHOW FULL TABLES WHERE table_type = 'BASE TABLE'";
$result = $conn->query($sql);

$tables = array();
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $table_name = $row['Tables_in_' . $db_name];
        $tables[$table_name] = array();

        // 获取表结构
        $desc_sql = "DESCRIBE $table_name";
        $desc_result = $conn->query($desc_sql);
        while($desc_row = $desc_result->fetch_assoc()) {
            $tables[$table_name][] = $desc_row;
        }
    }
}
//$tables = getAllTables();

// 生成网站目录结构
$site_dir = $db_name . '_site';
if (!file_exists($site_dir)) {
    mkdir($site_dir, 0777, true);
    mkdir("$site_dir/css", 0777, true);
    mkdir("$site_dir/js", 0777, true);
    mkdir("$site_dir/pages", 0777, true);
}

// 定义源目录和目标目录
$source_dir = __DIR__ . '/resource';
$target_dir = "$site_dir/resource";

// 检查源目录是否存在
if (file_exists($source_dir)) {
    // 递归拷贝目录的函数
    function recursive_copy($src, $dst) {
        $dir = opendir($src);
        if (!is_dir($dst)) {
            mkdir($dst, 0777, true);
        }
        while (false !== ($file = readdir($dir))) {
            if (($file != '.') && ($file != '..')) {
                if (is_dir($src . '/' . $file)) {
                    recursive_copy($src . '/' . $file, $dst . '/' . $file);
                } else {
                    copy($src . '/' . $file, $dst . '/' . $file);
                }
            }
        }
        closedir($dir);
    }

    // 执行拷贝操作
    recursive_copy($source_dir, $target_dir);
}

// 引入视图配置
require_once 'resource/view_names.php';

// 获取所有视图
$views = getAllViews();


// 生成导航HTML
$nav_html = "<div class=\"nav-container-wrapper\"><div class=\"nav-container\">

    <div class=\"nav-title\" data-target=\"basic-tables\">基本表</div>\n    <ul class=\"nav-list\" id=\"basic-tables\">\n";
foreach ($tables as $table_name => $fields) {
        $chinese_name = getChineseTableName($table_name);  
    $nav_html .= "        <li><a href=\"pages/{$table_name}_list.php\">{$chinese_name}</a></li>\n";
}
    $nav_html .= "    </ul>\n</div><div class=\"nav-container\">    <div class=\"nav-title\" data-target=\"views\">视图</div>\n    <ul class=\"nav-list\" id=\"views\">\n";

foreach ($views as $view_name) {
    global $viewConfig;
    $chinese_name = isset($viewConfig[$view_name]['name']) ? $viewConfig[$view_name]['name'] : $view_name;
    $nav_html .= "        <li><a href=\"pages/{$view_name}_list.php\">{$chinese_name}</a></li>\n";
}
$nav_html .= "    </ul>\n</div>\n</div>\n\n<script>\nfunction toggleNav(id) {\n    const list = document.getElementById(id);\n    list.classList.toggle('active');\n    \n    // 切换对应的标题的active类\n    const title = list.previousElementSibling;\n    title.classList.toggle('active');\n}\n// 默认展开基本表\ndocument.addEventListener('DOMContentLoaded', function() {\n    const tablesList = document.getElementById('tables');\n    tablesList.classList.add('active');\n    \n    // 为基本表标题添加active类\n    const tablesTitle = tablesList.previousElementSibling;\n    tablesTitle.classList.add('active');\n});\n</script>\n";
$nav_html2 = str_replace('pages/', '', $nav_html);
file_put_contents("$site_dir/nav_index.html", $nav_html);
file_put_contents("$site_dir/nav.html", $nav_html2);

// 生成首页
$index_content = "<!DOCTYPE html>\n<html lang=\"zh-CN\">\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <title>".WEB_NAME."</title>\n    <link rel=\"stylesheet\" href=\"resource/static/css/style.css\">\n    </head>\n<body>\n    <header><div class=\"container\" >  <h1>".WEB_NAME."</h1>\n        </div>\n    </header>\n\n          <nav><div id=\"static-nav\" class=\"container\"></div></nav>\n\n        <main class=\"container main-content\">\n            <h2>欢迎使用".WEB_NAME."</h2>\n            <p>请从左侧导航菜单选择要管理的数据表。</p>\n\n            <div class=\"table-info\">\n                <h3>数据库表信息</h3>\n                <ul>\n";

    foreach ($tables as $table_name => $fields) {
        $chinese_name = getChineseTableName($table_name);
        $index_content .= "                <li>{$chinese_name} (字段数量: ".count($fields).")</li>\n";
    }

$index_content .= "            </ul>
        </div>
    </main>

    <script src=\"resource/static/js/script.js\"></script>\n    
     <script>
    // 加载静态导航
    fetch('nav_index.html')
        .then(response => response.text())
        .then(html => {
            document.getElementById('static-nav').innerHTML = html;
        })
        .catch(error => console.error('加载导航失败:', error));
    </script>
</body>
</html>";
file_put_contents("$site_dir/index.html", $index_content);

/**
 * 获取表的外键信息
 * @param string $table_name 表名
 * @return array 外键信息数组
 */
function getForeignKeys($table_name) {
    global $conn;
    $safe_table_name = $conn->real_escape_string($table_name);
    $foreign_keys = array();
    // 获取数据库配置
    $db_name = getCurrentDatabaseName();
    $sql = "SELECT
                COLUMN_NAME,
                REFERENCED_TABLE_NAME,
                REFERENCED_COLUMN_NAME
              FROM
                INFORMATION_SCHEMA.KEY_COLUMN_USAGE
              WHERE
                TABLE_SCHEMA = '$db_name'
                AND TABLE_NAME = '$safe_table_name'
                AND REFERENCED_TABLE_NAME IS NOT NULL";

    $result = $conn->query($sql);
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $foreign_keys[$row['COLUMN_NAME']] = array(
                'referenced_table' => $row['REFERENCED_TABLE_NAME'],
                'referenced_column' => $row['REFERENCED_COLUMN_NAME']
            );
        }
    }
    return $foreign_keys;
}

// 从配置文件或数据库表comment中获取中文表名
function getChineseTableName($table_name) {
    global $conn; // 使用全局数据库连接
    
    // 首先尝试从配置文件获取视图的中文名称
    static $view_names = null;
    if ($view_names === null) {
        // 检查配置文件是否存在
        $config_file = __DIR__ . '/resource/view_names.php';
        if (file_exists($config_file)) {
            $view_names = include $config_file;
        } else {
            $view_names = array();
        }
    }
    
    // 如果是视图且配置文件中有对应的中文名称，则返回
    if (in_array($table_name, getAllViews()) && isset($view_names[$table_name]) && isset($view_names[$table_name]['name'])) {
        return $view_names[$table_name]['name'];
    }
    
    // 安全转义表名
    $safe_table_name = $conn->real_escape_string($table_name);
    
    // 尝试从数据库获取表的comment
    $sql = "SELECT TABLE_COMMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '$safe_table_name'";
    $result = $conn->query($sql);
    
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $comment = $row['TABLE_COMMENT'];
        
        // 如果comment不为空，则返回comment
        if (!empty($comment)) {
            return $comment;
        }
    }
    
    // 如果没有comment或查询失败，则返回原表名
    return $table_name;
}


// 获取表的主键
function getTablePrimaryKey($table_name) {
    global $conn;
    $sql = "DESCRIBE $table_name";
    $result = $conn->query($sql);
    while ($row = $result->fetch_assoc()) {
        if ($row['Key'] == 'PRI') {
            return $row['Field'];
        }
    }
    return '';
}

// 为每个表生成CRUD页面
foreach ($tables as $table_name => $fields) {
    // 跳过视图
    if (isView($conn, $table_name)) {
        continue;
    }
    $capitalized = ucfirst($table_name);
    $chinese_name = getChineseTableName($table_name);

    // 生成列表页面
    $list_content = "<?php
// 引入配置和SQL函数
require_once '../resource/config.php';
require_once '../resource/sql_commands.php';

// 获取当前页码，默认为1
\$page = isset(\$_GET['page']) ? intval(\$_GET['page']) : 1;
\$page_size = 10; // 每页显示数量

// 获取表名
\$table_name = '{$table_name}';

// 获取表的所有字段
\$table_fields = getTableFields(\$table_name);

// 处理搜索条件
\$search_conditions = array();
\$operators = array('eq' => '=', 'le' => '<=', 'ge' => '>=', 'like' => 'LIKE', 'nlike' => 'NOT LIKE');
\$logic_operators = array('and' => 'AND', 'or' => 'OR');

// 条件1
if (isset(\$_GET['field1']) && !empty(\$_GET['field1']) && isset(\$_GET['operator1']) && isset(\$operators[\$_GET['operator1']]) && isset(\$_GET['value1']) && !empty(\$_GET['value1'])) {
    \$field = \$_GET['field1'];
    \$operator = \$operators[\$_GET['operator1']];
    \$value = \$_GET['value1'];
    \$search_conditions[] = array(
        'field' => \$field,
        'operator' => \$operator,
        'value' => \$value
    );
}

// 条件2
if (isset(\$_GET['field2']) && !empty(\$_GET['field2']) && isset(\$_GET['operator2']) && isset(\$operators[\$_GET['operator2']]) && isset(\$_GET['value2']) && !empty(\$_GET['value2'])) {
    \$field = \$_GET['field2'];
    \$operator = \$operators[\$_GET['operator2']];
    \$value = \$_GET['value2'];
    \$logic = isset(\$_GET['logic']) && isset(\$logic_operators[\$_GET['logic']]) ? \$logic_operators[\$_GET['logic']] : 'AND';
    \$search_conditions[] = array(
        'field' => \$field,
        'operator' => \$operator,
        'value' => \$value,
        'logic' => \$logic
    );
}

// 函数已在上方定义，此处删除重复定义的残余代码

// 获取分页数据（支持搜索）
\$paged_data = getPagedDataWithSearch(\$table_name, \$page, \$page_size, \$search_conditions);
\$data = \$paged_data['data'];
\$total = \$paged_data['total'];
\$total_pages = \$paged_data['total_pages'];
\$current_page = \$paged_data['current_page'];

// 获取中文表名
\$chinese_name = '{$chinese_name}';
?>
<!DOCTYPE html
<html lang=\"zh-CN\">
<head>
    <meta charset=\"UTF-8\">
    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
    <title><?php echo \$chinese_name; ?>管理</title>
    <link rel=\"stylesheet\" href=\"../resource/static/css/style.css\">
    <style>
        .search-container {
            display: flex;
            align-items: center;
            margin-top: 10px;
            gap: 10px;
        }
        .search-group {
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        .search-container select, .search-container input {
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .search-container button {
            padding: 6px 12px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .search-container button:hover {
            background-color: #2980b9;
        }
    </style>
</head>
<body>
    <header>
        <div class=\"container\">
            <h1><?php echo WEB_NAME; ?></h1>
        </div>
    </header>

    <nav><div id=\"static-nav\" class=\"container\"></div></nav>

    <main class=\"container\">
        <div class=\"page-header\">
            <h2><?php echo \$chinese_name; ?>列表</h2>
            <a href=\"{$table_name}_add.php\" class=\"btn btn-success\">添加新记录</a>
            <a id=\"togglesearch\" href=\"#\" class=\"btn btn-success\">搜索</a>
            <style>
                #search-container {
                    display: none;
                }
            </style>
            <script>
                document.addEventListener('DOMContentLoaded', function() {
                    const toggleSearch = document.getElementById('togglesearch');
                    const searchContainer = document.querySelector('.search-container');
                    searchContainer.id = 'search-container';
                    
                    toggleSearch.addEventListener('click', function(e) {
                        e.preventDefault();
                        if (searchContainer.style.display === 'none' || searchContainer.style.display === '') {
                            searchContainer.style.display = 'block';
                        } else {
                            searchContainer.style.display = 'none';
                        }
                    });
                });
            </script>
            <!-- 搜索区域 -->
            <div class=\"search-container\">
                <form action=\"\" method=\"get\" id=\"search-form\">
                    <div class=\"search-group\">
                        <select name=\"field1\" id=\"field1\">
                            <option value=\"\">选择字段</option>
                            <?php foreach (\$table_fields as \$field): ?>
                                <option value=\"<?php echo \$field; ?>\" <?php echo isset(\$_GET['field1']) && \$_GET['field1'] == \$field ? 'selected' : ''; ?>>><?php echo getChineseFieldName(\$field, \$table_name); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <select name=\"operator1\" id=\"operator1\">
                            <option value=\"eq\" <?php echo isset(\$_GET['operator1']) && \$_GET['operator1'] == 'eq' ? 'selected' : ''; ?>>=</option>
                            <option value=\"le\" <?php echo isset(\$_GET['operator1']) && \$_GET['operator1'] == 'le' ? 'selected' : ''; ?>>&lt;=</option>
                            <option value=\"ge\" <?php echo isset(\$_GET['operator1']) && \$_GET['operator1'] == 'ge' ? 'selected' : ''; ?>>&gt;=</option>
                            <option value=\"like\" <?php echo isset(\$_GET['operator1']) && \$_GET['operator1'] == 'like' ? 'selected' : ''; ?>>包含</option>
                            <option value=\"nlike\" <?php echo isset(\$_GET['operator1']) && \$_GET['operator1'] == 'nlike' ? 'selected' : ''; ?>>不包含</option>
                        </select>
                        <input type=\"text\" name=\"value1\" id=\"value1\" placeholder=\"请输入值\" value=\"<?php echo isset(\$_GET['value1']) ? htmlspecialchars(\$_GET['value1']) : ''; ?>\" />
                    </div>

                    <div class=\"search-group\">
                        <select name=\"logic\" id=\"logic\">
                            <option value=\"and\" <?php echo isset(\$_GET['logic']) && \$_GET['logic'] == 'and' ? 'selected' : ''; ?>>并且</option>
                            <option value=\"or\" <?php echo isset(\$_GET['logic']) && \$_GET['logic'] == 'or' ? 'selected' : ''; ?>>或者</option>
                        </select>
                    </div>

                    <div class=\"search-group\">
                        <select name=\"field2\" id=\"field2\">
                            <option value=\"\">选择字段</option>
                            <?php foreach (\$table_fields as \$field): ?>
                                <option value=\"<?php echo \$field; ?>\" <?php echo isset(\$_GET['field2']) && \$_GET['field2'] == \$field ? 'selected' : ''; ?>><?php echo getChineseFieldName(\$field, \$table_name); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <select name=\"operator2\" id=\"operator2\">
                            <option value=\"eq\" <?php echo isset(\$_GET['operator2']) && \$_GET['operator2'] == 'eq' ? 'selected' : ''; ?>>=</option>
                            <option value=\"le\" <?php echo isset(\$_GET['operator2']) && \$_GET['operator2'] == 'le' ? 'selected' : ''; ?>>&lt;=</option>
                            <option value=\"ge\" <?php echo isset(\$_GET['operator2']) && \$_GET['operator2'] == 'ge' ? 'selected' : ''; ?>>&gt;=</option>
                            <option value=\"like\" <?php echo isset(\$_GET['operator2']) && \$_GET['operator2'] == 'like' ? 'selected' : ''; ?>>包含</option>
                            <option value=\"nlike\" <?php echo isset(\$_GET['operator2']) && \$_GET['operator2'] == 'nlike' ? 'selected' : ''; ?>>不包含</option>
                        </select>
                        <input type=\"text\" name=\"value2\" id=\"value2\" placeholder=\"请输入值\" value=\"<?php echo isset(\$_GET['value2']) ? htmlspecialchars(\$_GET['value2']) : ''; ?>\" />
                    </div>

                    <button type=\"submit\" form=\"search-form\">搜索</button>
                </form>
            </div>
        <div class=\"table-container\">\n            <table>\n                <thead>\n                    <tr>\n";

    foreach ($fields as $field) {
        $chinese_field_name = getChineseFieldName($field['Field'], $table_name);
        $list_content .= "                        <th>{$chinese_field_name}</th>\n";
    }
    $list_content .= "                        <th>操作</th>\n";
    $list_content .= "                    </tr>\n                </thead>\n                <tbody>\n";

    // 生成数据行
    $list_content .= "<?php\n";
    $list_content .= "// 获取表字段\n";
    $list_content .= "\$fields = getTableFields(\$table_name);\n\n";
    $list_content .= "if (!empty(\$data)) {\n";
    $list_content .= "    \$primary_keys = getTablePrimaryKeys(\$table_name);\n";
    $list_content .= "    foreach (\$data as \$row) {\n";
    $list_content .= "        echo '<tr>';\n";
    $list_content .= "        foreach (\$fields as \$field_name) {\n";
    $list_content .= "            echo '<td>' . \$row[\$field_name] . '</td>';\n";
    $list_content .= "        }\n";
    $list_content .= "        // 构建包含所有主键的URL参数\n";
    $list_content .= "        \$params = array();\n";
    $list_content .= "        foreach (\$primary_keys as \$pk) {\n";
    $list_content .= "            \$params[] = \$pk . '=' . urlencode(\$row[\$pk]);\n";
    $list_content .= "        }\n";
    $list_content .= "        \$param_str = implode('&', \$params);\n";
    $list_content .= "        echo '<td>';\n";
    $list_content .= "        echo '<a href=\"{$table_name}_edit.php?' . \$param_str . '\" class=\"btn\">编辑</a>';\n";
    $list_content .= "        echo '<a href=\"{$table_name}_delete.php?' . \$param_str . '\" class=\"btn btn-danger\">删除</a>';\n";
    $list_content .= "        echo '</td>';\n";
    $list_content .= "        echo '</tr>';\n";
    $list_content .= "    }\n";
    $list_content .= "}\n";
    $list_content .= "?>\n";
    $list_content .= "                </tbody>\n            </table>\n        </div>\n\n        <!-- 分页控件 -->\n        <div class=\"pagination\">\n            <p>共 <?php echo \$total; ?> 条记录，每页显示 <?php echo \$page_size; ?> 条，共 <?php echo \$total_pages; ?> 页</p>\n            <div>\n";
    // 首页和上一页（修正变量输出转义）
    $list_content .= "<?php if (\$current_page > 1): ?>\n";
    $list_content .= "                <a href=\"{$table_name}_list.php?page=1\" class=\"btn\">首页</a>\n";
    $list_content .= "                <a href=\"{$table_name}_list.php?page=<?php echo \$current_page - 1; ?>\" class=\"btn\">上一页</a>\n";
    $list_content .= "<?php endif; ?>\n";

    // 页码列表（修正循环变量输出）
    $list_content .= "<?php\n";
    $list_content .= "\$start_page = max(1, \$current_page - 2);\n";
    $list_content .= "\$end_page = min(\$total_pages, \$start_page + 4);\n";
    $list_content .= "for (\$i = \$start_page; \$i <= \$end_page; \$i++):\n";
    $list_content .= "    if (\$i == \$current_page): ?>\n";
    $list_content .= "                <span class=\"btn\" style=\"background-color: #2980b9;\"><?php echo \$i; ?></span>\n";
    $list_content .= "<?php else: ?>\n";
    $list_content .= "                <a href=\"{$table_name}_list.php?page=<?php echo \$i; ?>\" class=\"btn\"><?php echo \$i; ?></a>\n";
    $list_content .= "<?php endif; ?>\n";
    $list_content .= "<?php endfor; ?>\n";

    // 下一页和尾页（修正变量输出转义）
    $list_content .= "<?php if (\$current_page < \$total_pages): ?>\n";
    $list_content .= "                <a href=\"{$table_name}_list.php?page=<?php echo \$current_page + 1; ?>\" class=\"btn\">下一页</a>\n";
    $list_content .= "                <a href=\"{$table_name}_list.php?page=<?php echo \$total_pages; ?>\" class=\"btn\">末页</a>\n";
    $list_content .= "<?php endif; ?>\n";

    $list_content .= "            </div>\n        </div>\n    </main>\n\n    <script src=\"../resource/static/js/script.js\"></script>\n    <script>\n        // 检测URL参数中的错误\n        const urlParams = new URLSearchParams(window.location.search);\n        if (urlParams.has('error')) {\n            if (urlParams.get('error') === 'foreign_key') {\n                alert('无法删除该记录，因为它已被其他记录引用（外键约束）。\\n请先删除相关的引用记录，然后再尝试删除。');\n            } else if (urlParams.get('error') === 'delete') {\n                alert('删除记录失败。');\n            }\n        }\n    </script>\n    
     <script>
    // 加载静态导航
    fetch('../nav.html')
        .then(response => response.text())
        .then(html => {
            document.getElementById('static-nav').innerHTML = html;
        })
        .catch(error => console.error('加载导航失败:', error));
    </script></body>\n</html>";
    file_put_contents("$site_dir/pages/{$table_name}_list.php", $list_content);

    // 生成添加页面
    $add_content = "<!DOCTYPE html>
<html lang=\"zh-CN\">
<head>
    <meta charset=\"UTF-8\">
    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
    <title>添加{$chinese_name}</title>
    <link rel=\"stylesheet\" href=\"../resource/static/css/style.css\">
    <script src=\"../resource/static/js/script.js\"></script>
</head>
<body>
    <?php
    // 引入配置文件和函数
    require_once '../resource/config.php';
    require_once '../resource/sql_commands.php';

    

    // 获取表的外键信息
    function getForeignKeys(\$table_name) {
        global \$conn;
        if (!\$conn) {
            \$conn = getDbConnection();
        }
        \$safe_table_name = \$conn->real_escape_string(\$table_name);
        \$foreign_keys = array();
        \$db_name = getCurrentDatabaseName();
        // 使用区分大小写的查询，确保返回原始列名
        \$sql = 'SELECT COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME
                  FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
                  WHERE TABLE_SCHEMA = \'' . \$db_name . '\'
                    AND TABLE_NAME = \'' . \$safe_table_name . '\'
                    AND REFERENCED_TABLE_NAME IS NOT NULL';

        \$result = \$conn->query(\$sql);
        if (\$result && \$result->num_rows > 0) {
            while (\$row = \$result->fetch_assoc()) {
                // 保留列名的原始大小写
                \$foreign_keys[\$row['COLUMN_NAME']] = array(
                    'referenced_table' => \$row['REFERENCED_TABLE_NAME'],
                    'referenced_column' => \$row['REFERENCED_COLUMN_NAME']
                );
            }
        }
        return \$foreign_keys;
    }

    // 获取URL参数
    \$table_name = '{$table_name}';
    \$chinese_name = getChineseTableName2(\$table_name);
    \$capitalized = ucfirst(\$chinese_name);
    ?>

    <header>
        <div class=\"container\">
            <h1><?php echo WEB_NAME; ?></h1>
        </div>
    </header>

    <nav><div id=\"static-nav\" class=\"container\"></div></nav>

    <main class=\"container\">
        <h2>添加新{$capitalized}</h2>

        <form method=\"post\" action=\"{$table_name}_save.php\">
            <div class=\"form-group\">
            <?php
            // 获取当前表的外键信息
            \$foreign_keys = getForeignKeys(\$table_name);
            ?>
\n";

    // 获取当前表的外键信息
    $foreign_keys = getForeignKeys($table_name);
    // 添加调试日志
    foreach ($fields as $field) {
        // 跳过自动递增的主键
        if ($field['Extra'] == 'auto_increment') continue;

        $field_name = $field['Field'];
        $chinese_field_name = getChineseFieldName($field_name, $table_name);
        $add_content .= "                <label for=\"{$field_name}\">{$chinese_field_name}</label>\n";

        // 检查是否为外键
        if (isset($foreign_keys[$field_name])) {
            $referenced_table = $foreign_keys[$field_name]['referenced_table'];
            $referenced_column = $foreign_keys[$field_name]['referenced_column'];
            $chinese_referenced_table = getChineseTableName($referenced_table);

            // 使用generateSelectOptions函数生成下拉列表
            $add_content .= "                <select id=\"{$field_name}\" name=\"{$field_name}\" required>\n";
            $add_content .= "                    <option value=\"\">请选择{$chinese_referenced_table}</option>\n";
            $add_content .= "                    <?php echo generateSelectOptions('{$referenced_table}', '{$referenced_column}'); ?>\n";
            $add_content .= "                </select>\n";
        } elseif (strpos($field['Type'], 'int') !== false || strpos($field['Type'], 'float') !== false || strpos($field['Type'], 'double') !== false) {
            // 数字类型
            $add_content .= "                <input type=\"number\" id=\"{$field_name}\" name=\"{$field_name}\" required>\n";
        } elseif (strpos($field['Type'], 'date') !== false) {
            // 日期/时间类型
            $add_content .= "                <input type=\"date\" id=\"{$field_name}\" name=\"{$field_name}\" required>\n";
        } else {
            // 文本类型
            $add_content .= "                <input type=\"text\" id=\"{$field_name}\" name=\"{$field_name}\" required>\n";
        }
    }

    $add_content .= "            </div>
            <div class=\"form-actions\">
                <button type=\"submit\" class=\"btn btn-success\">保存</button>
                <a href=\"{$table_name}_list.php\" class=\"btn\">取消</a>
            </div>
        </form>
    </main>

    <script src=\"../resource/static/js/script.js\"></script>\n <script>
    // 加载静态导航
    fetch('../nav.html')
        .then(response => response.text())
        .then(html => {
            document.getElementById('static-nav').innerHTML = html;
        })
        .catch(error => console.error('加载导航失败:', error));
    </script>\n   <script>\n        // 检测URL参数中的错误\n        const urlParams = new URLSearchParams(window.location.search);\n        if (urlParams.has('error')) {\n            if (urlParams.get('error') === 'foreign_key') {\n                alert('无法删除该记录，因为它已被其他记录引用（外键约束）。\\n请先删除相关的引用记录，然后再尝试删除。');\n            } else if (urlParams.get('error') === 'delete') {\n                alert('删除记录失败。');\n            }\n        }\n    </script>
</body>
</html>";
file_put_contents("$site_dir/pages/{$table_name}_add.php", $add_content);

    // 生成编辑页面
    $edit_content = "<?php\n// 引入配置和SQL函数\nrequire_once '../resource/config.php';\nrequire_once '../resource/sql_commands.php';\n\n// 获取表名\n\$table_name = '{$table_name}';\n\n// 获取主键信息\n\$primary_keys = getTablePrimaryKeys(\$table_name);\n\$params = array();\nforeach (\$primary_keys as \$pk) {\n    if (!isset(\$_GET[\$pk])) {\n        header('Location: {$table_name}_list.php?error=notfound');\n        exit;\n    }\n    \$params[\$pk] = \$_GET[\$pk];\n}\n\n// 构建参数字符串\n\$param_str = http_build_query(\$params);\n\n// 自定义函数：通过参数获取记录\nfunction getRecordByParams(\$table_name, \$params) {\n    global \$conn;\n    \$safe_table_name = \$conn->real_escape_string(\$table_name);\n    \$where_clauses = array();\n    foreach (\$params as \$key => \$value) {\n        \$safe_key = \$conn->real_escape_string(\$key);\n        \$safe_value = \$conn->real_escape_string(\$value);\n        \$where_clauses[] = \"\$safe_key = '\$safe_value'\";\n    }\n    \$where_str = implode(' AND ', \$where_clauses);\n    \$sql = \"SELECT * FROM \$safe_table_name WHERE \$where_str\";\n    \$result = \$conn->query(\$sql);\n    if (\$result && \$result->num_rows > 0) {\n        return \$result->fetch_assoc();\n    }\n    return false;\n}\n\n// 获取表的外键信息\nfunction getForeignKeys(\$table_name) {\n    global \$conn;\n    if (!\$conn) {\n        \$conn = getDbConnection();\n    }\n    \$safe_table_name = \$conn->real_escape_string(\$table_name);\n    \$foreign_keys = array();\n\n    \$sql = \"SELECT\n                COLUMN_NAME,\n                REFERENCED_TABLE_NAME,\n                REFERENCED_COLUMN_NAME\n              FROM\n                INFORMATION_SCHEMA.KEY_COLUMN_USAGE\n              WHERE\n                TABLE_SCHEMA = '\". getCurrentDatabaseName() . \"'\n                AND TABLE_NAME = '\$safe_table_name'\n                AND REFERENCED_TABLE_NAME IS NOT NULL\";\n\n    \$result = \$conn->query(\$sql);\n    if (\$result && \$result->num_rows > 0) {\n        while (\$row = \$result->fetch_assoc()) {\n            \$foreign_keys[\$row['COLUMN_NAME']] = array(\n                'referenced_table' => \$row['REFERENCED_TABLE_NAME'],\n                'referenced_column' => \$row['REFERENCED_COLUMN_NAME']\n            );\n        }\n    }\n    return \$foreign_keys;\n}\n\n// 获取数据库连接\n\$conn = getDbConnection();\n\n// 获取记录数据\n\$record = getRecordByParams(\$table_name, \$params);\nif (!\$record) {\n    header('Location: {$table_name}_list.php?error=notfound');\n    exit;\n}\n\n// 获取中文表名\n\$chinese_name = '{$chinese_name}';\n?>\n<!DOCTYPE html>\n<html lang=\"zh-CN\">\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <title>编辑<?php echo \$chinese_name; ?></title>\n    <link rel=\"stylesheet\" href=\"../resource/static/css/style.css\">\n</head>\n<body>\n    <header>\n        <div class=\"container\">\n            <h1><?php echo WEB_NAME; ?></h1>\n        </div>\n    </header>\n\n    <nav><div id=\"static-nav\" class=\"container\"></div></nav>\n\n    <main class=\"container\">\n        <h2>编辑<?php echo \$chinese_name; ?></h2>\n\n        <form method=\"post\" action=\"{$table_name}_update.php?<?php echo \$param_str; ?>\">
            <div class=\"form-group\">\n";

    // 在循环前添加获取外键信息的代码
    $edit_content .= "            <?php\n            // 获取当前表的外键信息\n            \$foreign_keys = getForeignKeys(\$table_name);\n            ?>\n";

    foreach ($fields as $field) {
        // 跳过自动递增的主键
        if ($field['Extra'] == 'auto_increment') {
            $field_name = $field['Field'];
            $edit_content .= "                <label for=\"{$field['Field']}\">{$field['Field']}</label>\n";
            $edit_content .= "                <input type=\"text\" id=\"{$field['Field']}\" name=\"{$field['Field']}\" value=\"<?php echo \$record['{$field_name}']; ?>\" readonly>\n";
            continue;
        }

        $field_name = $field['Field'];
        $chinese_field_name = getChineseFieldName($field_name, $table_name);
        $edit_content .= "                <label for=\"{$field['Field']}\">{$chinese_field_name}</label>\n";

        // 检查是否为外键
        $edit_content .= "                <?php if (isset(\$foreign_keys['{$field_name}'])): ?>\n";
        $edit_content .= "                    <select id=\"{$field_name}\" name=\"{$field_name}\" required>\n";
        $edit_content .= "                        <option value=\"\">请选择</option>\n";
        $edit_content .= "                        <?php\n";
        $edit_content .= "                        \$ref_table = \$foreign_keys['{$field_name}']['referenced_table'];\n";
        $edit_content .= "                        \$ref_column = \$foreign_keys['{$field_name}']['referenced_column'];\n";
        $edit_content .= "                        echo generateSelectOptions(\$ref_table, \$ref_column, \$record['{$field_name}']);\n";
        $edit_content .= "                        ?>\n";
        $edit_content .= "                    </select>\n";
        $edit_content .= "                <?php else: ?>\n";

        // 根据字段类型生成不同的输入控件
        if (strpos($field['Type'], 'int') !== false || strpos($field['Type'], 'float') !== false || strpos($field['Type'], 'double') !== false) {
            $edit_content .= "                <input type=\"number\" id=\"{$field_name}\" name=\"{$field_name}\" required>\n";
        } elseif (strpos($field['Type'], 'date') !== false) {
            // 处理日期类型，确保格式为YYYY-MM-DD
            $edit_content .= "                <input type=\"date\" id=\"{$field_name}\" name=\"{$field_name}\" required>\n";
        } elseif (strpos($field['Type'], 'time') !== false) {
            // 处理时间类型
            $edit_content .= "                <input type=\"time\" id=\"{$field_name}\" name=\"{$field['Field']}\" value=\"<?php echo !empty(\$record['{$field_name}']) ? date('H:i', strtotime(\$record['{$field_name}'])) : ''; ?>\" required>\n";
        } else {
            $edit_content .= "                <input type=\"text\" id=\"{$field_name}\" name=\"{$field['Field']}\" value=\"<?php echo \$record['{$field_name}']; ?>\" required>\n";
        }

        $edit_content .= "                <?php endif; ?>\n";
    }

    $edit_content .= "            </div>\n            <div class=\"form-actions\">\n                <button type=\"submit\" class=\"btn btn-success\">更新</button>\n                <a href=\"{$table_name}_list.php\" class=\"btn\">取消</a>\n            </div>\n        </form>\n    </main>\n\n    <script src=\"../resource/static/js/script.js\"></script>\n<script>
    // 加载静态导航
    fetch('../nav.html')
        .then(response => response.text())
        .then(html => {
            document.getElementById('static-nav').innerHTML = html;
        })
        .catch(error => console.error('加载导航失败:', error));
    </script>\n</body>\n</html>";
    file_put_contents("$site_dir/pages/{$table_name}_edit.php", $edit_content);

    // 生成保存逻辑文件
    $save_content = "<?php
// 处理添加新记录的逻辑
require_once '../resource/config.php';
require_once '../resource/sql_commands.php';

// 获取表名和表单数据
\$table_name = '{$table_name}';
\$fields = \$_POST;

// 添加记录
\$result = addRecord(\$table_name, \$fields);

// 重定向回列表页面

// 调整判断逻辑，确保整数ID被正确识别为成功
if (\$result !== false) {
    header('Location: {$table_name}_list.php?success=add');
} else {
    header('Location: {$table_name}_add.php?error=1');
}
exit;
";
file_put_contents("$site_dir/pages/{$table_name}_save.php", $save_content);

    $update_content = "<?php
// 处理更新记录的逻辑
require_once '../resource/config.php';
require_once '../resource/sql_commands.php';

// 获取表名
\$table_name = '{$table_name}';

// 获取主键信息
\$primary_keys = getTablePrimaryKeys(\$table_name);
\$params = array();
foreach (\$primary_keys as \$pk) {
    if (!isset(\$_GET[\$pk])) {
        header('Location: {$table_name}_list.php?error=notfound');
        exit;
    }
    \$params[\$pk] = \$_GET[\$pk];
}

// 获取表单数据
\$fields = \$_POST;

// 更新记录
\$result = updateRecord(\$table_name, \$params, \$fields);

// 构建参数字符串
\$param_str = http_build_query(\$params);

// 重定向回列表页面
if (\$result) {
    header('Location: {$table_name}_list.php?success=update');
} else {
    header('Location: {$table_name}_edit.php?\$param_str&error=1');
}
exit;
";
file_put_contents("$site_dir/pages/{$table_name}_update.php", $update_content);

    $delete_content = "<?php
// 引入配置和SQL函数
require_once '../resource/config.php';
require_once '../resource/sql_commands.php';

// 获取表名
\$table_name = '{$table_name}';

// 获取主键信息
\$primary_keys = getTablePrimaryKeys(\$table_name);
\$params = array();
foreach (\$primary_keys as \$pk) {
    if (!isset(\$_GET[\$pk])) {
        header('Location: {$table_name}_list.php?error=notfound');
        exit;
    }
    \$params[\$pk] = \$_GET[\$pk];
}

// 删除记录
\$result = deleteRecord(\$table_name, \$params);

// 检查是否有外键约束错误
\$error_type = '';
if (!\$result) {
    // 读取错误日志的最后一行
    \$log_file = '../../delete_debug.log';
    if (file_exists(\$log_file)) {
        \$lines = file(\$log_file);
        \$last_line = end(\$lines);
        if (strpos(\$last_line, 'foreign key constraint fails') !== false) {
            \$error_type = 'foreign_key';
        }
    }
}

// 构建参数字符串
\$param_str = http_build_query(\$params);

// 重定向回列表页面
if (\$result) {
    header('Location: {$table_name}_list.php?success=delete');
} else {
    if (\$error_type == 'foreign_key') {
        header('Location: {$table_name}_list.php?error=foreign_key');
    } else {
        header('Location: {$table_name}_list.php?error=delete');
    }
}
exit;
";
file_put_contents("$site_dir/pages/{$table_name}_delete.php", $delete_content);
}

// 为视图生成list页面
// 获取所有视图
$views = getAllViews();

// 为每个视图生成list页面
foreach ($views as $view_name) {
    $capitalized = ucfirst($view_name);
    $chinese_name = getChineseTableName($view_name);
    $base_tables = getViewBaseTables($view_name);
    
    // 生成列表页面
    $list_content = "<?php
    // 引入配置和SQL函数
require_once '../resource/config.php';
require_once '../resource/sql_commands.php';
require_once '../resource/view_names.php';
// 假设此处 $view_name 变量已存在，从视图配置中获取当前视图的 manage 值，默认为 1
    \$manage_value = isset(\$viewConfig['$view_name']['manage']) ? \$viewConfig['$view_name']['manage'] : 1;
// 获取当前页码，默认为1
\$page = isset(\$_GET['page']) ? intval(\$_GET['page']) : 1;
\$page_size = 10; 
// 每页显示数量
// 获取表的所有字段
\$table_fields = getTableFields('$view_name');

// 处理搜索条件
\$search_conditions = array();
\$operators = array('eq' => '=', 'le' => '<=', 'ge' => '>=', 'like' => 'LIKE', 'nlike' => 'NOT LIKE');
\$logic_operators = array('and' => 'AND', 'or' => 'OR');

// 条件1
if (isset(\$_GET['field1']) && !empty(\$_GET['field1']) && isset(\$_GET['operator1']) && isset(\$operators[\$_GET['operator1']]) && isset(\$_GET['value1']) && !empty(\$_GET['value1'])) {
    \$field = \$_GET['field1'];
    \$operator = \$operators[\$_GET['operator1']];
    \$value = \$_GET['value1'];
    \$search_conditions[] = array(
        'field' => \$field,
        'operator' => \$operator,
        'value' => \$value
    );
}

// 条件2
if (isset(\$_GET['field2']) && !empty(\$_GET['field2']) && isset(\$_GET['operator2']) && isset(\$operators[\$_GET['operator2']]) && isset(\$_GET['value2']) && !empty(\$_GET['value2'])) {
    \$field = \$_GET['field2'];
    \$operator = \$operators[\$_GET['operator2']];
    \$value = \$_GET['value2'];
    \$logic = isset(\$_GET['logic']) && isset(\$logic_operators[\$_GET['logic']]) ? \$logic_operators[\$_GET['logic']] : 'AND';
    \$search_conditions[] = array(
        'field' => \$field,
        'operator' => \$operator,
        'value' => \$value,
        'logic' => \$logic
    );
}
// 获取分页数据
\$table_name = '{$view_name}';
\$paged_data = getPagedDataWithSearch(\$table_name, \$page, \$page_size, \$search_conditions);
\$data = \$paged_data['data'];
\$total = \$paged_data['total'];
\$total_pages = \$paged_data['total_pages'];
\$current_page = \$paged_data['current_page'];
// 获取中文表名
\$chinese_name = '{$chinese_name}';?>


<!DOCTYPE html>\n<html lang=\"zh-CN\">\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <title><?php echo \$chinese_name; ?>管理</title>\n    <link rel=\"stylesheet\" href=\"../resource/static/css/style.css\">\n</head>\n<body>\n    <header>\n        <div class=\"container\">\n            <h1><?php echo WEB_NAME; ?></h1>\n        </div>\n    </header>\n\n    <nav><div id=\"static-nav\" class=\"container\"></div></nav>\n\n    <main class=\"container\">\n        <div class=\"page-header\">\n            <h2><?php echo \$chinese_name; ?>列表(视图)</h2>\n           

        <?php if (\$manage_value == 1) { ?>
        <a href=\"{$base_tables[0]}_add.php\" class=\"btn btn-success\">添加新记录</a>\n      
        <?php } ?>
 <a id=\"togglesearch\" href=\"#\" class=\"btn btn-success\">搜索</a>
            <style>
                #search-container {
                    display: none;
                }
                    .search-container {
            display: flex;
            align-items: center;
            margin-top: 10px;
            gap: 10px;
        }
        .search-group {
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        .search-container select, .search-container input {
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .search-container button {
            padding: 6px 12px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .search-container button:hover {
            background-color: #2980b9;
        }
            </style>
            <script>
                document.addEventListener('DOMContentLoaded', function() {
                    const toggleSearch = document.getElementById('togglesearch');
                    const searchContainer = document.querySelector('.search-container');
                    searchContainer.id = 'search-container';
                    
                    toggleSearch.addEventListener('click', function(e) {
                        e.preventDefault();
                        if (searchContainer.style.display === 'none' || searchContainer.style.display === '') {
                            searchContainer.style.display = 'block';
                        } else {
                            searchContainer.style.display = 'none';
                        }
                    });
                });
            </script>
            <!-- 搜索区域 -->
            <div class=\"search-container\">
                <form action=\"\" method=\"get\" id=\"search-form\">
                    <div class=\"search-group\">
                        <select name=\"field1\" id=\"field1\">
                            <option value=\"\">选择字段</option>
                            <?php foreach (\$table_fields as \$field): ?>
                                <option value=\"<?php echo \$field; ?>\" <?php echo isset(\$_GET['field1']) && \$_GET['field1'] == \$field ? 'selected' : ''; ?>>><?php echo getChineseFieldName(\$field, \$table_name); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <select name=\"operator1\" id=\"operator1\">
                            <option value=\"eq\" <?php echo isset(\$_GET['operator1']) && \$_GET['operator1'] == 'eq' ? 'selected' : ''; ?>>=</option>
                            <option value=\"le\" <?php echo isset(\$_GET['operator1']) && \$_GET['operator1'] == 'le' ? 'selected' : ''; ?>>&lt;=</option>
                            <option value=\"ge\" <?php echo isset(\$_GET['operator1']) && \$_GET['operator1'] == 'ge' ? 'selected' : ''; ?>>&gt;=</option>
                            <option value=\"like\" <?php echo isset(\$_GET['operator1']) && \$_GET['operator1'] == 'like' ? 'selected' : ''; ?>>包含</option>
                            <option value=\"nlike\" <?php echo isset(\$_GET['operator1']) && \$_GET['operator1'] == 'nlike' ? 'selected' : ''; ?>>不包含</option>
                        </select>
                        <input type=\"text\" name=\"value1\" id=\"value1\" placeholder=\"请输入值\" value=\"<?php echo isset(\$_GET['value1']) ? htmlspecialchars(\$_GET['value1']) : ''; ?>\" />
                    </div>

                    <div class=\"search-group\">
                        <select name=\"logic\" id=\"logic\">
                            <option value=\"and\" <?php echo isset(\$_GET['logic']) && \$_GET['logic'] == 'and' ? 'selected' : ''; ?>>并且</option>
                            <option value=\"or\" <?php echo isset(\$_GET['logic']) && \$_GET['logic'] == 'or' ? 'selected' : ''; ?>>或者</option>
                        </select>
                    </div>

                    <div class=\"search-group\">
                        <select name=\"field2\" id=\"field2\">
                            <option value=\"\">选择字段</option>
                            <?php foreach (\$table_fields as \$field): ?>
                                <option value=\"<?php echo \$field; ?>\" <?php echo isset(\$_GET['field2']) && \$_GET['field2'] == \$field ? 'selected' : ''; ?>><?php echo getChineseFieldName(\$field, \$table_name); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <select name=\"operator2\" id=\"operator2\">
                            <option value=\"eq\" <?php echo isset(\$_GET['operator2']) && \$_GET['operator2'] == 'eq' ? 'selected' : ''; ?>>=</option>
                            <option value=\"le\" <?php echo isset(\$_GET['operator2']) && \$_GET['operator2'] == 'le' ? 'selected' : ''; ?>>&lt;=</option>
                            <option value=\"ge\" <?php echo isset(\$_GET['operator2']) && \$_GET['operator2'] == 'ge' ? 'selected' : ''; ?>>&gt;=</option>
                            <option value=\"like\" <?php echo isset(\$_GET['operator2']) && \$_GET['operator2'] == 'like' ? 'selected' : ''; ?>>包含</option>
                            <option value=\"nlike\" <?php echo isset(\$_GET['operator2']) && \$_GET['operator2'] == 'nlike' ? 'selected' : ''; ?>>不包含</option>
                        </select>
                        <input type=\"text\" name=\"value2\" id=\"value2\" placeholder=\"请输入值\" value=\"<?php echo isset(\$_GET['value2']) ? htmlspecialchars(\$_GET['value2']) : ''; ?>\" />
                    </div>

                    <button type=\"submit\" form=\"search-form\">搜索</button>
                </form>
            </div>
 </div>\n\n        <div class=\"table-container\">\n            <table>\n                <thead>\n                    <tr>\n";

    // 获取视图字段
    $view_fields = getTableFields($view_name);
    foreach ($view_fields as $field) {
        $chinese_field_name = getChineseFieldName($field, $view_name);
        $list_content .= "                        <th>{$chinese_field_name}</th>\n";
    }
    if($manage_value == 1) 
        $list_content .= "<th>操作</th>";
    
    $list_content .= " </tr>\n                </thead>\n                <tbody>\n";

    // 生成数据行
    $list_content .= "<?php\n";
    $list_content .= "// 获取视图字段\n";
    $list_content .= "\$fields = getTableFields(\$table_name);\n\n";
    $list_content .= "if (!empty(\$data)) {\n";
    $list_content .= "    foreach (\$data as \$row) {\n";
    $list_content .= "        echo '<tr>';\n";
    $list_content .= "        foreach (\$fields as \$field_name) {\n";
    $list_content .= "            echo '<td>' . \$row[\$field_name] . '</td>';\n";
    $list_content .= "        }\n";
    $list_content .= "        // 构建包含所有主键的URL参数\n";
    $list_content .= "        \$params = array();\n";
    $list_content .= "        \$primary_keys = getPrimaryKeysByView('{$view_name}');\n";
    $list_content .= "        foreach (\$primary_keys as \$view_pk => \$pk) {\n";
    $list_content .= "            \$params[] = \$pk . '=' . urlencode(\$row[\$view_pk]);\n";
    $list_content .= "        }\n";
    $list_content .= "        \$param_str = implode('&', \$params);\n";
    
    if($manage_value == 1) {
        $list_content .= "        echo '<td>';\n";
        $list_content .= "        echo '<a href=\"{$base_tables[0]}_edit.php?' . \$param_str . '\" class=\"btn\">编辑</a>';";
        $list_content .= "        echo '<a href=\"{$base_tables[0]}_delete.php?' . \$param_str . '\" class=\"btn btn-danger\">删除</a>';";
        $list_content .= "        echo '</td>';\n";
    }
    $list_content .= "        echo '</tr>';\n";
    $list_content .= "    }\n";
    $list_content .= "} else {\n";
    $list_content .= "    echo '<tr><td colspan=\"' . count(\$fields) . '\">没有找到记录</td></tr>';\n";
    $list_content .= "}\n";
    $list_content .= "?>\n";
    $list_content .= "                </tbody>\n            </table>\n        </div>\n\n        <!-- 分页控件 -->\n        <div class=\"pagination\">\n            <p>共 <?php echo \$total; ?> 条记录，每页显示 <?php echo \$page_size; ?> 条，共 <?php echo \$total_pages; ?> 页</p>\n            <div>\n";

 // 首页和上一页
    $list_content .= "<?php if (\$current_page > 1): ?>\n";
    $list_content .= "                <a href=\"{$view_name}_list.php?page=1\" class=\"btn\">首页</a>\n";
    $list_content .= "                <a href=\"{$view_name}_list.php?page=<?php echo \$current_page - 1; ?>\" class=\"btn\">上一页</a>\n";
    $list_content .= "<?php endif; ?>\n";

    // 页码列表
    $list_content .= "<?php\n";
    $list_content .= "\$start_page = max(1, \$current_page - 2);\n";
    $list_content .= "\$end_page = min(\$total_pages, \$start_page + 4);\n";
    $list_content .= "for (\$i = \$start_page; \$i <= \$end_page; \$i++):\n";
    $list_content .= "    if (\$i == \$current_page): ?>\n";
    $list_content .= "                <span class=\"btn\" style=\"background-color: #2980b9;\"><?php echo \$i; ?></span>\n";
    $list_content .= "<?php else: ?>\n";
    $list_content .= "                <a href=\"{$view_name}_list.php?page=<?php echo \$i; ?>\" class=\"btn\"><?php echo \$i; ?></a>\n";
    $list_content .= "<?php endif; ?>\n";
    $list_content .= "<?php endfor; ?>\n";

    // 下一页和尾页
    $list_content .= "<?php if (\$current_page < \$total_pages): ?>\n";
    $list_content .= "                <a href=\"{$view_name}_list.php?page=<?php echo \$current_page + 1; ?>\" class=\"btn\">下一页</a>\n";
    $list_content .= "                <a href=\"{$view_name}_list.php?page=<?php echo \$total_pages; ?>\" class=\"btn\">末页</a>\n";
    $list_content .= "<?php endif; ?>\n";

    $list_content .= "            </div>\n        </div>\n    </main>\n\n    <script src=\"../resource/static/js/script.js\"></script>\n<script>
    // 加载静态导航
    fetch('../nav.html')
        .then(response => response.text())
        .then(html => {
            document.getElementById('static-nav').innerHTML = html;
        })
        .catch(error => console.error('加载导航失败:', error));
    </script>\n</body>\n</html>";
    file_put_contents("$site_dir/pages/{$view_name}_list.php", $list_content);
}


// 关闭数据库连接
$conn->close();

echo "网站生成成功！文件已保存到 " . realpath($site_dir) . " 目录";
?>